// VBConversions Note: VB project level imports
using System.Data;
using DevExpress.XtraEditors.Controls;
using System.Diagnostics;
using System.Xml.Linq;
using DevExpress.XtraEditors.Repository;
using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using System.Configuration;
using System.Collections;
using DevExpress.XtraEditors;
using System.Data.Sql;
using Microsoft.SqlServer;
using System.Windows.Forms;
using System;
using DevExpress.XtraReports;
using Microsoft.SqlServer.Management.Smo;
using DevExpress;
using System.Linq;
using System.IO;
// End of VB project level imports



namespace SCIEF.SysBFW.CommonExt
{
	namespace Base
	{
		/// <summary>
		/// Connection will be use to provide a connection to the database and provide Command Object from that connection
		/// </summary>
		/// <remarks></remarks>
		public sealed class Connection
		{
			private static SqlConnection _db;
			public static string InfoMessage;
			public static SqlConnection Db
			{
				get
				{
					//Dim swatch As Stopwatch = New Stopwatch()
					//swatch.Start()
					int tryAgain = 0;
					_db = new SqlConnection();
					_db.InfoMessage += new System.Data.SqlClient.SqlInfoMessageEventHandler(_db_InfoMessage);
					_db.ConnectionString = AppManager.ConnectionString;
					_db.Open();
					//swatch.Stop()
					//Console.WriteLine("OpenDB: " + swatch.Elapsed.ToString)
					while (_db.State == ConnectionState.Connecting && tryAgain <= 1000)
					{
						tryAgain++;
						//pour quand la connection est très slow...
					}
					return _db;
				}
			}
			
			public static void CloseConnection()
			{
				AppManager.IsConnected = false;
				AppManager.ConnectionString = string.Empty;
				if (_db != null && _db.State == ConnectionState.Open)
				{
					_db.Close();
				}
				if (_db != null)
				{
					SqlConnection.ClearAllPools();
				}
			}
			
			public static SqlCommand Command()
			{
				SqlCommand cmd = Db.CreateCommand();
				cmd.CommandTimeout = 0; //no limits...
				return cmd;
			}
			
			private static void _db_InfoMessage(object sender, System.Data.SqlClient.SqlInfoMessageEventArgs e)
			{
				SqlError err = default(SqlError);
				System.Text.StringBuilder sb = new System.Text.StringBuilder();
				foreach (SqlError tempLoopVar_err in e.Errors)
				{
					err = tempLoopVar_err;
					sb.AppendLine(err.Message);
				}
				if (e.Errors.Count > 0)
				{
					//outstandingissue: Elle ne leve pas si executer au runtime...aleblanc
					//MyApplication_UnhandledException du ApplicationEvents.vb devrait l'attraper...
					//Throw New Exception(sb.ToString)
				}
			}
		}
	}
	
	
	
}
